// 列表页/垃圾回收页/星标页+ 分页：获取列表表格的列表请求
import { useRequest } from "ahooks";
import { getQuestionListService } from "../services/question";
import { useSearchParams } from "react-router-dom";
import {
  LIST_SEARCH_KEY,
  LIST_PAGE_INDEX_KEY,
  LIST_PAGE_SIZE_KEY,
  LIST_PAGE_INDEX,
  LIST_PAGE_SIZE,
} from "../constant";

// 在星标页、垃圾回收页使用时，对列表数据做一个筛选
type optionType = {
  isStar: boolean;
  isDelete: boolean;
};

function useLoadQuestionListData(opt: Partial<optionType> = {}) {
  const [searchParams] = useSearchParams();
  const { isDelete, isStar } = opt;
  //   console.log("keyword", searchParams.get("keyword"));

  // refesh : 返回手动刷新的方法
  const { data, loading, error , refresh} = useRequest(
    async () => {
      const keyword = searchParams.get(LIST_SEARCH_KEY) || "";
      const pageIndex =
        parseInt(searchParams.get(LIST_PAGE_INDEX_KEY) || "") ||
        LIST_PAGE_INDEX;
      const pageSize =
        parseInt(searchParams.get(LIST_PAGE_SIZE_KEY) || "") || LIST_PAGE_SIZE;

      const data = await getQuestionListService({
        keyword,
        isDelete,
        isStar,
        pageIndex,
        pageSize,
      });
      return data;
    },
    {
      refreshDeps: [searchParams], // 配置项： url改变时重新请求
    }
  );

  return { data, error, loading ,refresh };
}

export default useLoadQuestionListData;
